﻿using StackExchange.Redis;
using System;
using System.Runtime.InteropServices.ComTypes;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var varlockKey = "lockKey";

            var varstock = 5; //商品库存

            var vartaskCount = 10; //线程数量

            RedisHelper.RemoveKey(varlockKey); //先删除 key

            var id = Guid.NewGuid().ToString("N");


            for (int i = 0; i < vartaskCount; i++)
            {
                do
                {
                    var isDataExist = RedisHelper.CheckKeyExist(varlockKey);//先判断 key是否存在
                    if (!isDataExist)
                    {
                        RedisHelper.SetKeyExprie(varlockKey,$"{i}",10);
                        break;
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(10)); //休息1秒再尝试获取锁
                } while (true);

                if (RedisHelper.LockTake("_key"+varlockKey,id))//确保方法执行完   成功占锁
                {
                    Console.WriteLine($"{i}******拿到了锁,开始消费");

                    if (varstock <= 0)
                    {
                        Console.WriteLine($"库存不足,线程: {i}抢购失败!");

                        RedisHelper.RemoveKey(varlockKey);

                        return;
                    }

                    varstock--; //更新库存数量

                    Console.WriteLine($" {i}消费完毕!剩余 {varstock}个");
                }

                //业务处理完后,释放锁.
                RedisHelper.LockRelease("_key"+ varlockKey, id);
                RedisHelper.RemoveKey(varlockKey);//删除缓存
            }


        }
    }
}
